package com.ttbj.core.util;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import java.lang.reflect.Field;

/**
 * 转化类
 * 
 * @author
 */
public class DtoTransitionUtils {
	private static Logger logger = Logger.getLogger(DtoTransitionUtils.class);

	public static Object trans(Class<?> cls, Object object) {
		if (null == cls || object == null) {
			throw new IllegalArgumentException("class or object is null");
		}
		try {
			Object instance = cls.newInstance();
			PropertyUtils.copyProperties(instance, object); // 关键语句
			return instance;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("trans error", e);
		}
		return null;
	}

	public static Object combineSydwCore(Object sourceBean, Object targetBean) {
		Class<? extends Object> sourceBeanClass = sourceBean.getClass();
		Class<? extends Object> targetBeanClass = targetBean.getClass();
		Field[] sourceFields = sourceBeanClass.getDeclaredFields();
		Field[] targetFields = targetBeanClass.getDeclaredFields();
		for (int i = 0; i < sourceFields.length; i++) {
			Field sourceField = sourceFields[i];
			Field targetField = targetFields[i];
			sourceField.setAccessible(true);
			targetField.setAccessible(true);
			try {
				if (!(sourceField.get(sourceBean) == null)) {
					targetField.set(targetBean, sourceField.get(sourceBean));
				}
			} catch (IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return targetBean;

	}
}
